package org.renwei.ml;

import com.google.common.base.Charsets;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by renwei on 16/9/2.
 */
public class DataHelper {
    /**
     * 读取文件资源
     * {humidity=[high, high], windy=[FALSE, TRUE], outlook=[sunny, sunny], play=[no, no], temperature=[hot, hot]}
     *
     * @param path
     * @return
     */
    public static Map<String, List<String>> read(String path) {
        File file = new File(path);
        List<String> flist = null;
        try {
            flist = Files.readLines(file, Charsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<List<String>> ds = Lists.newArrayList();
        for (String line : flist) {
            String[] data = line.split(",");
            List<String> tmp = Lists.newArrayList();
            for (int i = 0; i < data.length; i++) {
                tmp.add(data[i]);
            }
            ds.add(tmp);
        }

        Map<String, List<String>> dataSet = Maps.newHashMap();
        for (int i = 0; i < ds.get(0).size(); i++) {
            List<String> newds = Lists.newArrayList();
            for (int j = 0; j < ds.size(); j++) {
                newds.add(ds.get(j).get(i));
            }
            String key = newds.get(0);
            newds.remove(0);
            dataSet.put(key, newds);
        }

        return dataSet;
    }

    /**
     * 统计每个属性在集合中出现的次数
     * useage:
     * for (Multiset.Entry<String> entry : DataHelper.getTypeCounts(dataSet).entrySet()) {
     * entry.getElement();entry.getCount()
     *
     * @param dataSet
     */
    public static Multiset<String> getTypeCounts(List<String> dataSet) {
        Multiset<String> labelMultiset = HashMultiset.create();
        labelMultiset.addAll(dataSet);
        return labelMultiset;
    }

    /**
     * 获取key的index list
     *
     * @param key
     * @param dataSet
     * @return
     */
    public static List<Integer> getIndex(String key, List<String> dataSet) {
        List<Integer> indexList = Lists.newArrayList();
        for (int i = 0; i < dataSet.size(); i++) {
            if (key.equals(dataSet.get(i))) {
                indexList.add(Integer.valueOf(i));
            }
        }
        return indexList;
    }

    /**
     * 根据index获取数据集
     *
     * @param indexList
     * @param dataSet
     * @return
     */
    public static List<String> getSubSet(List<Integer> indexList, List<String> dataSet) {
        List<String> subSet = Lists.newArrayList();
        for (Integer i : indexList) {
            subSet.add(dataSet.get(i));
        }
        return subSet;
    }
}
